#include "GeoBox.h"

GeoBox::GeoBox(float mWidth, float mHeight, float mDepth, int mWSegment, int mHSegment, int mDSegment)
		:Geometry(),m_width(mWidth), m_height(mHeight),
		 m_wSegment(mWSegment),
		 m_hSegment(mHSegment),m_depth(mDepth),m_dSegment(mDSegment)
{
	makeData();
	setup();
}

void GeoBox::makeData()
{
	//x y z
	makePlane(0,1,2,1,m_width,m_height,m_depth,m_wSegment,m_hSegment);
	makePlane(0,1,2,-1,m_width,m_height,-m_depth,m_wSegment,m_hSegment);
	//y z x
 	makePlane(1,2,0,1,m_height,m_depth,m_width,m_hSegment,m_dSegment);
 	makePlane(1,2,0,-1,m_height,m_depth,-m_width,m_hSegment,m_dSegment);
	//z x y
	makePlane(2,0,1,1,m_depth,m_width,m_height,m_dSegment,m_wSegment);
	makePlane(2,0,1,-1,m_depth,m_width,-m_height,m_dSegment,m_wSegment);
}

void GeoBox::makePlane(int u, int v, int w, int dir, float width, float height, float depth, int wSegment,
                         int hSegment)
{
	float w_half=width/2.0;
	float h_half=height/2.0;
	float d_half=depth/2.0;
	float dx=width/wSegment;
	float dy=height/hSegment;
	auto offset=vertices.size();
	//计算顶点坐标和纹理坐标
	for(int iy=0;iy<=hSegment;++iy)
	{
		float vy=iy*dy-h_half;
		float ty=1- static_cast<float>(iy)/hSegment;
		for(int ix=0;ix<=wSegment;++ix)
		{
			float vx=ix*dx-w_half;
			float tx=static_cast<float>(ix)/wSegment;
			glm::vec3 vec;
			vec[u]=vx*dir;
			vec[v]=vy*dir;
			vec[w]=d_half;
			this->vertices.push_back({vec,{tx,ty}});
		}
	}
	//计算索引
	for(uint iy=0;iy<hSegment;++iy)
		for(uint ix=0;ix<wSegment;++ix)
		{
			uint a=offset+iy*(wSegment+1)+ix;
			uint b=a+1;
			uint c=offset+(iy+1)*(wSegment+1)+ix;
			uint d=c+1;
			this->indices.push_back(a);
			this->indices.push_back(c);
			this->indices.push_back(d);
			this->indices.push_back(a);
			this->indices.push_back(b);
			this->indices.push_back(d);
		}


}
